﻿using Abp.Application.Services.Dto;
using Abp.Extensions;
using DHJ.Cost.TreeStructure.Dto;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace DHJ.Cost.TreeStructure
{
    public class TreeStructureAppService: CostAppServiceBase, ITreeStructureAppService
    {
        //TreeBaseManager<TreeNodeBase> TreeBaseManager { get; set; }
        private readonly ITreeBaseManager<TreeNodeBase> _treeBaseManager;

        public TreeStructureAppService(ITreeBaseManager<TreeNodeBase> treeBaseManager)
        {
            _treeBaseManager = treeBaseManager;
        }

        public async Task<ListResultDto<TreeNodeListDto>> GetAllRoot( )
        {

            var treeNode = _treeBaseManager.GetAllRootNode();
            return new ListResultDto<TreeNodeListDto>(ObjectMapper.Map<List<TreeNodeListDto>>(treeNode));
        }

        public async Task<ListResultDto<TreeNodeListDto>> GetChildren(string code)
        {
            var nodes = code.IsNullOrEmpty() ? _treeBaseManager.GetAllRootNode() : _treeBaseManager.GetChildren(code);

            return new ListResultDto<TreeNodeListDto>(ObjectMapper.Map<List<TreeNodeListDto>>(nodes));
        }

       public async Task<TreeNodeDto> CreateTreeNode(TreeNodeInput input)
        {
            var treeNode = new TreeNodeBase(input.NodeName,input.NodeValue);
            if (input.ParentId!=0)
            {
                _treeBaseManager.InsertNode(treeNode, input.ParentId);
            }
            else
            {
                _treeBaseManager.InsertNode(treeNode);
            }
            
            await CurrentUnitOfWork.SaveChangesAsync();

            return ObjectMapper.Map<TreeNodeDto>(treeNode);

        }
        public async Task<TreeNodeDto> MoveTreeNode(MoveTreeNodeInput input)
        {
            await _treeBaseManager.MoveNode(input.NodeId,input.TargetId);
            var treeNode = _treeBaseManager.GetNode(input.NodeId);

            return  ObjectMapper.Map<TreeNodeDto>(treeNode);
        }

       

        public async Task DeleteTreeNode(EntityDto<long> input)
        {
            await _treeBaseManager.DelNode(input.Id);
        }

        public async Task DeleteTree(EntityDto<long> input)
        {
            await _treeBaseManager.DelTree(input.Id);
        }

    













    }
}
